<template>
  <div>
    <!-- 顶部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- card -->
    <el-card class="box-card">
      <!-- 消息提醒框 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- step 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 最外层有个大的表单嵌套 -->
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-position="top">
        <!-- tabs -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="handleTabClick1"
        >
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="cateChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <el-form-item v-for="item in manyList" :key="item.attr_id" :label="item.attr_name">
              <!-- 渲染的多选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(val,index) in item.attr_vals" :label="val" :key="index" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-form-item v-for="item in onlyList" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
            <el-upload
              multiple
              action="https://www.liulongbin.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :headers="headerObj"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <br />
            <el-button type="primary" @click="addSubmit">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 预览大图的弹框 -->
      <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
        <img :src="this.previewPath" alt="图片" width="100%" />
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { reqAllCateList, reqParamsList, reqAddGood, reqUpload } from '../../api/index'
export default {
  data () {
    return {
      // step 和 tabs 切换的联动索引值
      activeIndex: '0',

      // 添加表单需要的数据
      addForm: {
        // 商品名称
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 分类的id
        goods_cat: [],
        // 图片的数组
        pics: [],
        // 商品简介
        goods_introduce: '',
        // 商品的参数
        attrs: []
      },
      // 添加表单的校验规则
      addRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
      },
      // 所有商品列表的数据
      cateList: [],

      // 级联选择器的配置项
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 动态参数列表
      manyList: [],
      // 静态参数列表
      onlyList: [],

      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },

      // 图片的大图预览
      dialogVisible: false,
      // 预览的图片路径
      previewPath: '',

      content: '',

    }
  },
  methods: {
    // 获取分类列表的数据
    async getCateList () {
      const result = await reqAllCateList(3)
      console.log(result)
      if (result.meta.status === 200) {
        this.cateList = result.data

      } else {
        this.$message.error(result.meta.msg);
      }
    },

    // 获取分类动态参数列表
    async getManyList () {
      const result = await reqParamsList(this.addForm.goods_cat[2], 'many')
      console.log(result)
      if (result.meta.status === 200) {
        result.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })
        this.manyList = result.data
      } else {
        this.$message.error(result.meta.msg);
      }
    },
    // 获取分类静态参数列表
    async getOnlyList () {
      const result = await reqParamsList(this.addForm.goods_cat[2], 'only')
      console.log(result)
      if (result.meta.status === 200) {
        this.onlyList = result.data
      } else {
        this.$message.error(result.meta.msg);
      }
    },
    // 级联选择器的变化
    cateChange () {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },

    // 将要离开面板的钩子函数
    beforeLeave (activeName, oldActiveName) {
      console.log(oldActiveName, this.addForm.goods_cat.length, this.addForm.goods_name.trim())
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3 || this.addForm.goods_name === '') {
        this.$message.error('请填写相关参数')
        return false
      }
    },

    // 点击tab的函数
    handleTabClick1 () {
      if (this.activeIndex === '1') {
        this.getManyList()
      } else if (this.activeIndex === '2') {
        this.getOnlyList()
      }
    },

    // 图片移除
    handleRemove (file) {
      // 1. 找到需要删除图片的临时路径
      const img = file.response.data.tmp_path
      // 2. 从pics数组中找到该临时路径的索引值
      const index = this.addForm.pics.findIndex(item => item.pic === img)
      // 3. 从数组中移除
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm)
    },

    // 图片预览
    handlePreview (file) {
      console.log(file)
      this.previewPath = file.response.data.url
      this.dialogVisible = true
    },

    // 上传成功
    handleUploadSuccess (response) {
      console.log(response)
      // 1. 拼接一个对象给后台的上传
      const imgInfo = { "pic": response.data.tmp_path }
      // 2. 将图片文件保存到表单中
      this.addForm.pics.push(imgInfo)
      console.log(this.addForm)
    },

    // 添加商品的校验
    addSubmit () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请填写相关参数')
        } else {
          // 将动态参数和静态参数转成数组
          this.manyList.forEach((item) => {
            const info = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
            this.addForm.attrs.push(info)
          })

          this.onlyList.forEach(item => {
            const info = { attr_id: item.attr_id, attr_value: item.attr_vals }
            this.addForm.attrs.push(info)
          })

          // 先将 goods_cat 转成字符串(需要深拷贝)
          let obj = JSON.parse(JSON.stringify(this.addForm))
          obj.goods_cat = obj.goods_cat.join(',')
          // console.log(obj)

          const result = await reqAddGood(obj)
          if (result.meta.status === 201) {
            this.$message.success('添加商品成功')
            this.$router.history.replace('goods')

          } else {
            this.$message.error(result.meta.msg);
          }
        }

      });
    }


  },
  created () {
    this.getCateList()
  },
}
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 15px;

  .el-tabs {
    margin-top: 30px;
  }

  .el-cascader {
    width: 100%;
  }
  .el-checkbox {
    margin: 0 10px 10px 0 !important;
  }
}
</style>

/**
tab：
1. 第一页跳转至其他页，要先确保第一页的数据都有填上（表单验证），并且级联选择器中，选择三级的才能跳转
before-leave： 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换

2. 点击面板的时候页签的时候发起请求
tab-click： tab 被选中时触发

3. 商品参数
 点击发起请求
 页面使用for遍历生成attr_name和attr_vals形成的多选框

4. 商品属性
 点击发起请求
 表单渲染

5. 图片上传
内容分析：
(1)action：图片上传到后台的API地址，不能写相对路径，应该填写完整的决定路径
action="upload" × 因为请求的地址是8080端口的 http://localhost:8080/#/addgood/upload 但需要上传的路径为http://127.0.0.1:8888/api/private/v1/upload ，因此需要些绝对地址

(2)on-preview：图片预览事件
(3)on-remove: 图片移除事件
(4)list-type: 文件列表的类型

<el-upload
  class="upload-demo"
  action="https://jsonplaceholder.typicode.com/posts/"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :file-list="fileList"
  list-type="picture">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
</el-upload>

难点：upload组件自身封装了一套ajax组件，但是接口文档中必须要携带token才能完成请求，所以要为upload组件添加请求头 headers，其内部需要定义 Authorization = window.sessionStorage.getItem('token')


上传图片成功：监听图片上传成功的事件
handleSuccess(response) {
    console.log(response)
    // 1. 拼接得到一个图片信息对象
    const picInfo = { pic: response.data.tmp_path }
    // 2. 将图片信息对象，push 到pics数组中
    this.addForm.pics.push(picInfo)
    console.log(this.addForm)
}


移除图片：
 handleRemove(file) {
    // console.log(file)
    // 1. 获取将要删除的图片的临时路径
    const filePath = file.response.data.tmp_path
    // 2. 从 pics 数组中，找到这个图片对应的索引值
    const i = this.addForm.pics.findIndex(x => x.pic === filePath)
    // 3. 调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
    this.addForm.pics.splice(i, 1)
    console.log(this.addForm)
}

图片的预览效果：
添加dialog弹框，放入可以直接访问的URL地址而不是临时地址


6. 商品内容
安装富文本编译器 vue-quill-editor


移除生产环境的所有console https://www.npmjs.com/package/babel-plugin-transform-remove-console
babel-plugin-transform-remove-console 插件

 */
